import java.util.Arrays;
import java.util.HashMap;
import java.util.TreeSet;

/**
* @description: 846. 一手顺子
* @author hewei
* @date 2022/9/2 21:20
* @version 1.0
*/

public class IsNStraightHand {

    public boolean isNStraightHand1(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) return false;
        HashMap<Integer, Integer> map = new HashMap<>();
        TreeSet<Integer> set = new TreeSet<>();
        for (int i : hand) {
            set.add(i);
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        while (!set.isEmpty()) {
            Integer poll = set.pollFirst();
            while (map.containsKey(poll)) {
                for (int i = 0; i < groupSize; i++) {
                    if (!map.containsKey(poll + i)) return false;
                    map.put(poll + i, map.get(poll + i) - 1);
                    if (map.get(poll + i) == 0) map.remove(poll + i);
                }
            }
        }
        return true;
    }

    public boolean isNStraightHand(int[] hand, int groupSize) {
        if (hand.length % groupSize != 0) return false;
        Arrays.sort(hand);
        HashMap<Integer, Integer> map = new HashMap<>();
        for (int i : hand) {
            map.put(i, map.getOrDefault(i, 0) + 1);
        }
        for (int i : hand) {
            if (!map.containsKey(i)) continue;
            for (int j = 0; j < groupSize; j++) {
                if (!map.containsKey(j + i)) return false;
                map.put(j + i, map.get(j + i) - 1);
                if (map.get(j + i) == 0) map.remove(j + i);
            }
        }
        return true;
    }
}
